<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useGetProductCategoryOptions, useGetProductListToSelect, useSaveProductListOfProject } from '@fl/api/purchase'
import { SearchForm, SearchTable } from '@fl/components'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { cloneDeep } from 'lodash-es'

const props = defineProps<{
    projectId: string
}>()
const visible = defineModel<boolean>('visible', { required: true })

const initialState = {} as any
const state = ref(cloneDeep(initialState))

const dialogTitle = '选择组合商品'

const selectedProducts = ref<any[]>([])

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const useGetProductListToSelectParams = computed(() => ({
    objQuery: {
        ...searchConditions.value,
        projectId: props.projectId,
    },
    page: tablePage.currentPage,
    size: tablePage.pageSize,
}))

const {
    data: productPageData,
    isLoading: isGetProductPageLoading,
    total: productTotal,
} = useGetProductListToSelect(useGetProductListToSelectParams)
const { data: productCategoryOptionsData, isLoading: isGetProductCategoryOptionsLoading } = useGetProductCategoryOptions()
const { isPending: isSaveProductListOfProjectPending, mutate: saveProductListOfProject } = useSaveProductListOfProject()

const isSubmitLoading = computed(() => isSaveProductListOfProjectPending.value)

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isGetProductCategoryOptionsLoading.value)

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: '组合商品类目',
        options: productCategoryOptionsData as OptionsType,
        prop: 'categoryId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '组合商品名称',
        prop: 'productName',
        valueType: 'copy',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const tableRef = ref()
const isTableLoading = computed(() => isGetProductPageLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { type: 'checkbox', width: 60 },
        { field: 'categoryName', title: '组合商品类目' },
        { field: 'productName', title: '组合商品名称' },
        // { field: 'taxExcludedPrice', title: '除税价' },
        // { field: 'rate', title: '税率' },
        // { field: 'taxIncludedPrice', title: '含税价' },
    ],
    height: 544,
})

watchEffect(() => {
    tableData.value = cloneDeep(productPageData.value)
    tablePage.total = productTotal.value
})

watch(() => tableData.value, (newValue) => {
    if (Array.isArray(newValue)) {
        const $table = (tableRef.value as any)?.tableInstance
        if ($table) {
            const checkedRows = newValue.filter((item: any) => selectedProducts.value.find((selectedItem: any) => item.id === selectedItem.id))
            nextTick(() => {
                $table.setCheckboxRow(checkedRows, true)
            })
        }
    }
})
// #endregion

// #region UI Listener
function cancel() {
    visible.value = false
}

function closed() {
    state.value = cloneDeep(initialState)
    formRef.value?.formInstance?.formInstance.resetFields()
    selectedProducts.value = []
}

function onTableCheckboxChange(data: any) {
    const { records } = data
    for (const currentPageSelectedItem of records) {
        const savedItemIndex = selectedProducts.value.findIndex(((item: any) => item.id === currentPageSelectedItem.id))
        if (savedItemIndex === -1) {
            selectedProducts.value.push(currentPageSelectedItem)
        }
    }
    const unselectedRecords = tableData.value
        .filter((item: any) => !records.find((currentPageSelectedItem: any) => item.id === currentPageSelectedItem.id))
    for (const currentPageUnselectedItem of unselectedRecords) {
        const savedItemIndex = selectedProducts.value.findIndex(((item: any) => item.id === currentPageUnselectedItem.id))
        if (savedItemIndex > -1) {
            selectedProducts.value.splice(savedItemIndex, 1)
        }
    }
}

function onConfirmBtnClick() {
    if (selectedProducts.value.length) {
        const params = selectedProducts.value.map((item: any) => ({
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            id: item.id,
            productName: item.productName,
            projectId: props.projectId,
        }))
        saveProductListOfProject(params, {
            onSuccess() {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
    else {
        cancel()
    }
}
// #endregion
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                close-on-press-escape
                width="1300"
                @cancel="cancel"
                @closed="closed"
    >
        <el-card mb-20
                 shadow="never"
        >
            <el-skeleton v-if="isFormLoading"
                         animated
            />

            <SearchForm v-else
                        ref="formRef"
                        v-model="state"
                        :columns="columns"
                        submit-text="查询"
                        :row-props="{ gutter: 40 }"
                        @submit="submit"
                        @reset="reset"
            />
        </el-card>

        <el-card shadow="never">
            <SearchTable v-bind="gridOptions"
                         ref="tableRef"
                         v-model:pager="tablePage"
                         :loading="isTableLoading"
                         :data="tableData"
                         @checkbox-change="onTableCheckboxChange"
            />
        </el-card>

        <template #footer>
            <div class="mx-auto">
                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onConfirmBtnClick"
                >
                    确定
                </SubmitBtn>

                <el-button @click="cancel">
                    取消
                </el-button>
            </div>
        </template>
    </PlusDialog>
</template>
